<?php

namespace App\Http\Controllers;

use App\Script;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ScriptController extends Controller
{
    /**
     * 脚本更新登录所得钻石
     *
     * @param  Request
     * @return Response
     */
    public function updateLogin()
    {
        try{
            //每日登录----钻*用户价值（用户价值=昨日个人消费钻石数/昨日消费用户中平均消费金额）
            //读取所有用户id，匹配昨日消费/昨日用户平均消费
            $startTime = strtotime(date("Y-m-d",strtotime("-1 day"))." 00:00:00");
            $endTime = strtotime(date("Y-m-d",strtotime("-1 day"))." 23:59:59");
//            $startTime = strtotime(date("Y-m-d")." 00:00:00");
//            $endTime = strtotime(date("Y-m-d")." 23:59:59");
            $yesterdayDiamond = DB::table('diamond_use')->whereIn('diamond_type',[11,12])->whereBetween('create_time', [$startTime, $endTime])->avg('diamond');
            $setting = DB::table('diamond_setting')->value('login');
            $userIds = DB::table('users')->pluck('id');
            foreach($userIds as $k=>$v){
                $myDiamond = DB::table('diamond_use')->where('users_id','=',$v)->whereIn('diamond_type',[11,12])->whereBetween('create_time', [$startTime, $endTime])->sum('diamond');
                $todayLoginDiamonds = round($myDiamond/$yesterdayDiamond*$setting,2);
                DB::table('users')->where('id','=',$v)->update(array('today_login_diamonds'=>$todayLoginDiamonds));
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }
}
